// 存储任务的数组
let tasks = [];
let historyTasks = [];

// 象限颜色定义
const quadrantColors = {
    '1': '#e57373',
    '2': '#81c784',
    '3': '#ffd54f',
    '4': '#64b5f6'
};

// DOM 元素
const taskForm = document.getElementById('task-form');
const taskTitleInput = document.getElementById('task-title');
const taskDescriptionInput = document.getElementById('task-description');
const taskQuadrantSelect = document.getElementById('task-quadrant');
const quadrants = document.querySelectorAll('.quadrant');
const modal = document.getElementById('task-details-modal');
const modalTitle = document.getElementById('modal-task-title');
const modalDescription = document.getElementById('modal-task-description');
const closeModalBtn = document.querySelector('.close');
const completeTaskBtn = document.getElementById('complete-task-btn');
const editTaskBtn = document.getElementById('edit-task-btn');
const confirmDialog = document.getElementById('confirm-dialog');
const confirmYesBtn = document.getElementById('confirm-yes');
const confirmNoBtn = document.getElementById('confirm-no');
const historyTasksContainer = document.querySelector('.history-tasks');

// 编辑任务模态框元素
const editModal = document.getElementById('edit-task-modal');
const editTaskForm = document.getElementById('edit-task-form');
const editTaskTitleInput = document.getElementById('edit-task-title');
const editTaskDescriptionInput = document.getElementById('edit-task-description');
const editTaskDeadlineInput = document.getElementById('edit-task-deadline');
const closeEditModalBtn = document.querySelector('.close-edit');


// 当前选中的任务ID
let selectedTaskId = null;

// 页面加载时从文件系统加载任务
document.addEventListener('DOMContentLoaded', () => {
    loadTasksFromLocalStorage();
    loadHistoryTasksFromLocalStorage();
    // 不需要在这里调用renderTasks和renderHistoryTasks
    // 因为它们已经在加载函数中被调用了
    setupDragAndDrop();
});

// 表单提交事件
taskForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // 获取表单数据
    const title = taskTitleInput.value.trim();
    const description = taskDescriptionInput.value.trim();
    const quadrant = taskQuadrantSelect.value;

    // 创建新任务
    const deadline = document.getElementById('task-deadline').value;
    const newTask = {
        id: Date.now(), // 使用时间戳作为唯一ID
        title,
        description,
        quadrant,
        deadline: deadline || null, // 保存截止时间，如果未设置则为null
        // 根据象限计算坐标
        x: quadrant === '1' || quadrant === '3' ? Math.random() * 40 + 10 : Math.random() * -40 - 10, // 正负区分紧急程度
        y: quadrant === '1' || quadrant === '2' ? Math.random() * 40 + 10 : Math.random() * -40 - 10  // 正负区分重要程度
    };

    // 添加到任务数组
    tasks.push(newTask);

    // 保存到本地存储
    saveTasksToLocalStorage();

    // 渲染任务
    renderTasks();

    // 重置表单
    taskForm.reset();
});

// 关闭模态框
closeModalBtn.addEventListener('click', () => {
    modal.style.display = 'none';
});

// 点击模态框外部关闭
window.addEventListener('click', (e) => {
    if (e.target === modal) {
        modal.style.display = 'none';
    }
});

// 检查任务截止时间并更新位置
function checkDeadlines() {
    const now = new Date();
    let hasChanges = false;

    tasks.forEach(task => {
        if (!task.deadline) return;

        const deadline = new Date(task.deadline);
        const timeLeft = deadline - now;
        const hoursLeft = timeLeft / (1000 * 60 * 60);

        // 获取当前象限
        const currentQuadrant = task.quadrant;
        let newQuadrant = currentQuadrant;
        // 根据剩余时间调整象限
        if (hoursLeft <= 10 && hoursLeft > 0) {
            // 不足10小时且未过期，移动到第一象限（重要且紧急）
            newQuadrant = 1;
            task.x = Math.random() * 40 + 10;
            task.y = Math.random() * 40 + 10;
            hasChanges = true; // 标记有变化
        } else if (hoursLeft <= 48 && hoursLeft > 10) {
            // 不足48小时但超过10小时，移动到紧急象限
            if (String(currentQuadrant) === '2') {
                newQuadrant = 1; // 从重要不紧急移到重要且紧急
                task.x = Math.random() * 40 + 10;
                task.y = Math.random() * 40 + 10;
                hasChanges = true; // 标记有变化
            } else if (String(currentQuadrant) === '3' || String(currentQuadrant) === '4') {
                newQuadrant = 3; // 从不重要不紧急或不重要紧急移到不重要但紧急
                task.x = Math.random() * 40 + 10;
                task.y = Math.random() * -40 - 10;
                hasChanges = true; // 标记有变化
            }
        }

        // 更新任务象限
        if (newQuadrant !== currentQuadrant) {
            task.quadrant = newQuadrant;
            hasChanges = true;
        }
    });

    if (hasChanges) {
        saveTasksToLocalStorage();
        renderTasks(); // 重新渲染任务
    }
}

// 每分钟检查一次截止时间
setInterval(checkDeadlines, 60000);

// 检测是否为移动设备
function isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
        (window.matchMedia && window.matchMedia('(max-width: 768px)').matches);
}

// 渲染所有任务
function renderTasks() {
    // 清空任务容器
    const tasksContainer = document.querySelector('.tasks-container');
    const taskList = document.querySelector('.task-list');
    tasksContainer.innerHTML = '';
    taskList.innerHTML = '';

    // 检测是否为移动设备
    const isMobile = isMobileDevice();

    // 按截止时间排序任务
    const sortedTasks = [...tasks].sort((a, b) => {
        if (!a.deadline) return 1;
        if (!b.deadline) return -1;
        return new Date(a.deadline) - new Date(b.deadline);
    });

    // 渲染每个任务
    sortedTasks.forEach(task => {
        // 创建任务列表项
        const taskListItem = document.createElement('div');
        taskListItem.className = 'task-list-item';
        // 使用全局定义的quadrantColors
        taskListItem.style.backgroundColor = quadrantColors[task.quadrant];

        const taskTitle = document.createElement('div');
        taskTitle.className = 'task-title';
        taskTitle.textContent = task.title;

        const taskDeadline = document.createElement('div');
        taskDeadline.className = 'task-deadline';
        taskDeadline.textContent = task.deadline ? new Date(task.deadline).toLocaleString() : '未设置截止时间';

        taskListItem.appendChild(taskTitle);
        taskListItem.appendChild(taskDeadline);

        // 点击列表项显示任务详情
        taskListItem.addEventListener('click', () => {
            showTaskDetails(task);
        });

        taskList.appendChild(taskListItem);
        // 创建任务元素
        const taskElement = document.createElement('div');
        taskElement.className = 'task-item';
        taskElement.setAttribute('data-id', task.id);
        taskElement.setAttribute('data-title', task.title);
        taskElement.setAttribute('data-description', task.description);
        taskElement.setAttribute('data-deadline', task.deadline ? new Date(task.deadline).toLocaleString() : '未设置');

        // 计算剩余时间
        let leftDays = 0;
        let leftHours = 0;
        let totalLeftHours = 0;

        if (task.deadline) {
            const now = new Date();
            const deadline = new Date(task.deadline);
            const timeLeft = deadline - now;
            totalLeftHours = timeLeft / (1000 * 60 * 60);
            leftDays = Math.floor(totalLeftHours / 24);
            leftHours = Math.floor(totalLeftHours % 24);

            // 为剩余时间少于2天的任务添加特殊类
            if (totalLeftHours <= 48 && totalLeftHours > 10) {
                taskElement.classList.add('less-than-day');
            }
            // 为剩余时间少于10小时的任务添加特殊类
            else if (totalLeftHours <= 10 && totalLeftHours > 0) {
                taskElement.classList.add('less-than-hours');
            }
        }

        // taskElement.setAttribute('data-leftDays', leftDays);
        // taskElement.setAttribute('data-leftHours', leftHours);
        taskElement.setAttribute('data-leftInfo', task.deadline ?
            `剩余时间：${String(leftDays)} 天 ${String(leftHours)}小时` :
            '剩余时间：未设置'
        );

        // 在移动设备上不设置draggable属性，使用触摸事件处理拖拽
        if (!isMobile) {
            taskElement.draggable = true;
        }

        // 设置位置（将坐标转换为百分比位置）
        const xPos = 50 + task.x; // 将x坐标转换为相对于容器中心的百分比
        const yPos = 50 - task.y; // 将y坐标转换为相对于容器中心的百分比
        taskElement.style.left = `${xPos}%`;
        taskElement.style.top = `${yPos}%`;

        // 根据象限设置任务点的颜色
        // 使用全局定义的quadrantColors

        // 为过期任务设置灰色背景
        if (totalLeftHours < 0) {
            taskElement.style.backgroundColor = '#808080'; // 灰色
            taskElement.style.boxShadow = '0 0 5px #808080';
        }
        // 为剩余时间少于10小时的任务设置红色背景
        else if (taskElement.classList.contains('less-than-hours')) {
            taskElement.style.backgroundColor = '#ff0000';
            // 不设置boxShadow，因为动画会处理
        } else {
            taskElement.style.backgroundColor = quadrantColors[task.quadrant];
            taskElement.style.boxShadow = `0 0 5px ${quadrantColors[task.quadrant]}`;
        }

        // 点击事件 - 显示详情（PC端）
        if (!isMobile) {
            taskElement.addEventListener('click', () => {
                showTaskDetails(task);
            });

            // 右键事件 - 删除任务（仅PC端）
            taskElement.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                selectedTaskId = task.id;
                showConfirmDialog();
            });
        }
        // 移动端的触摸事件在setupDragAndDrop中处理

        // 添加到容器
        tasksContainer.appendChild(taskElement);
    });
}

// 渲染历史任务
function renderHistoryTasks() {
    historyTasksContainer.innerHTML = '';
    historyTasks.forEach(task => {
        const historyTaskElement = document.createElement('div');
        historyTaskElement.className = 'history-task-item';
        historyTaskElement.textContent = task.title;
        historyTaskElement.addEventListener('click', () => {
            showTaskDetails(task);
        });
        historyTasksContainer.appendChild(historyTaskElement);
    });
}

// 显示任务详情
function showTaskDetails(task) {
    selectedTaskId = task.id;
    modalTitle.textContent = task.title;

    // 清除已存在的截止时间元素
    const existingDeadlineInfo = modalDescription.parentNode.querySelector('.deadline-info');
    if (existingDeadlineInfo) {
        existingDeadlineInfo.remove();
    }

    // 创建截止时间元素
    let deadlineInfo = '';
    if (task.deadline) {
        const deadline = new Date(task.deadline);
        const now = new Date();
        const timeLeft = deadline - now;
        const daysLeft = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
        const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60)) % 24;
        deadlineInfo = `
            <div class="deadline-info">
                截止时间: ${deadline.toLocaleString()}<br>
                剩余时间: ${timeLeft > 0 ? `${daysLeft} 天 ${hoursLeft} 小时` : '已过期'}
            </div>
        `;
    } else {
        deadlineInfo = `
            <div class="deadline-info">
                截止时间: 无
            </div>
        `;
    }

    // 设置任务描述
    modalDescription.textContent = task.description;

    // 在标题和描述之间插入截止时间信息
    if (deadlineInfo) {
        const deadlineElement = document.createElement('div');
        deadlineElement.innerHTML = deadlineInfo;
        modalDescription.parentNode.insertBefore(deadlineElement, modalDescription);
    }
    modal.style.display = 'block';

    const isHistoryTask = historyTasks.some(t => t.id === task.id);
    completeTaskBtn.style.display = isHistoryTask ? 'none' : 'block';
    editTaskBtn.style.display = isHistoryTask ? 'none' : 'block';

    // 显示或隐藏恢复任务按钮
    const restoreBtn = document.getElementById('restore-task-btn');
    if (restoreBtn) {
        restoreBtn.style.display = isHistoryTask ? 'block' : 'none';
    }
}

// 显示确认对话框
function showConfirmDialog() {
    confirmDialog.style.display = 'block';
}

// 完成任务
function completeTask() {
    const task = tasks.find(t => t.id === selectedTaskId);
    if (task) {
        // 从任务列表中移除
        tasks = tasks.filter(t => t.id !== selectedTaskId);
        // 添加到历史任务
        historyTasks.push(task);
        // 保存更新
        saveTasksToLocalStorage();
        saveHistoryTasksToLocalStorage();
        // 重新渲染
        renderTasks();
        renderHistoryTasks();
        // 关闭模态框
        modal.style.display = 'none';
    }
}

// 恢复任务
function restoreTask() {
    const task = historyTasks.find(t => t.id === selectedTaskId);
    if (task) {
        // 从历史任务中移除
        historyTasks = historyTasks.filter(t => t.id !== selectedTaskId);
        // 添加到任务列表
        tasks.push(task);
        // 保存更新
        saveTasksToLocalStorage();
        saveHistoryTasksToLocalStorage();
        // 重新渲染
        renderTasks();
        renderHistoryTasks();
        // 关闭模态框
        modal.style.display = 'none';
    }
}

// 初始化恢复任务按钮
document.addEventListener('DOMContentLoaded', () => {
    const restoreBtn = document.createElement('button');
    restoreBtn.id = 'restore-task-btn';
    restoreBtn.className = 'restore-btn';
    restoreBtn.textContent = '恢复任务';
    restoreBtn.style.display = 'none';
    restoreBtn.addEventListener('click', restoreTask);

    const modalContent = document.querySelector('.modal-content');
    modalContent.appendChild(restoreBtn);
});

// 检测是否为移动设备
function isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
        (window.matchMedia && window.matchMedia('(max-width: 768px)').matches);
}

// 设置拖拽相关事件
function setupDragAndDrop() {
    const tasksContainer = document.querySelector('.tasks-container');
    const isMobile = isMobileDevice();
    let longPressTimer;
    let isDragging = false;
    let currentDragElement = null;
    let startX, startY;

    if (isMobile) {
        // 移动端触摸事件处理

        // 触摸开始 - 可能是长按开始拖拽
        tasksContainer.addEventListener('touchstart', (e) => {
            const taskElement = e.target.closest('.task-item');
            if (!taskElement) return;

            // 记录开始位置
            const touch = e.touches[0];
            startX = touch.clientX;
            startY = touch.clientY;
            currentDragElement = taskElement;

            // 设置长按定时器，750ms后触发拖拽
            longPressTimer = setTimeout(() => {
                isDragging = true;
                taskElement.classList.add('dragging');
                // 视觉反馈
                taskElement.style.opacity = '0.7';
            }, 750);
        }, { passive: false });

        // 触摸移动 - 如果是拖拽状态则移动任务点
        tasksContainer.addEventListener('touchmove', (e) => {
            if (!isDragging || !currentDragElement) return;
            e.preventDefault(); // 防止页面滚动

            const touch = e.touches[0];
            const containerRect = tasksContainer.getBoundingClientRect();
            const x = touch.clientX - containerRect.left;
            const y = touch.clientY - containerRect.top;

            // 计算相对于容器中心的坐标
            const relativeX = ((x / containerRect.width) - 0.5) * 100;
            const relativeY = (0.5 - (y / containerRect.height)) * 100;

            // 避免在坐标轴上放置任务点
            if (Math.abs(relativeX) < 2 || Math.abs(relativeY) < 2) return;

            // 确定象限
            const quadrant = getQuadrantFromCoordinates(relativeX, relativeY);
            if (!quadrant) return;

            // 更新任务点位置
            currentDragElement.style.left = `${(x / containerRect.width) * 100}%`;
            currentDragElement.style.top = `${(y / containerRect.height) * 100}%`;
        }, { passive: false });

        // 触摸结束 - 完成拖拽或触发点击
        tasksContainer.addEventListener('touchend', (e) => {
            // 清除长按定时器
            clearTimeout(longPressTimer);

            // 如果不是拖拽状态，则是普通点击
            if (!isDragging && currentDragElement) {
                // 获取任务ID并显示详情
                const taskId = parseInt(currentDragElement.getAttribute('data-id'));
                const task = tasks.find(t => t.id === taskId);
                if (task) {
                    showTaskDetails(task);
                }
            } else if (isDragging && currentDragElement) {
                // 完成拖拽，更新任务位置
                const taskId = parseInt(currentDragElement.getAttribute('data-id'));
                const task = tasks.find(t => t.id === taskId);
                if (!task) {
                    resetDragState();
                    return;
                }

                const containerRect = tasksContainer.getBoundingClientRect();
                const touch = e.changedTouches[0];
                const x = touch.clientX - containerRect.left;
                const y = touch.clientY - containerRect.top;

                // 计算相对于容器中心的坐标
                const relativeX = ((x / containerRect.width) - 0.5) * 100;
                const relativeY = (0.5 - (y / containerRect.height)) * 100;

                // 避免在坐标轴上放置任务点
                if (Math.abs(relativeX) < 2 || Math.abs(relativeY) < 2) {
                    resetDragState();
                    return;
                }

                // 确定象限并更新任务
                const quadrant = getQuadrantFromCoordinates(relativeX, relativeY);
                if (!quadrant) {
                    resetDragState();
                    return;
                }

                // 更新任务数据
                task.x = relativeX;
                task.y = relativeY;
                task.quadrant = quadrant;

                // 保存并重新渲染
                saveTasksToLocalStorage();
                renderTasks();
            }

            resetDragState();
        }, { passive: false });

        // 触摸取消 - 重置状态
        tasksContainer.addEventListener('touchcancel', () => {
            resetDragState();
        });

        // 重置拖拽状态的函数
        function resetDragState() {
            if (currentDragElement) {
                currentDragElement.classList.remove('dragging');
                currentDragElement.style.opacity = '1';
            }
            isDragging = false;
            currentDragElement = null;
            clearTimeout(longPressTimer);
        }
    } else {
        // PC端拖拽事件处理（保持原有逻辑）
        // 任务拖拽开始
        document.addEventListener('dragstart', (e) => {
            const taskElement = e.target.closest('.task-item');
            if (taskElement) {
                taskElement.classList.add('dragging');
                e.dataTransfer.setData('text/plain', taskElement.getAttribute('data-id'));
            }
        });

        // 任务拖拽结束
        document.addEventListener('dragend', (e) => {
            const taskElement = e.target.closest('.task-item');
            if (taskElement) {
                taskElement.classList.remove('dragging');
            }
        });

        // 处理拖拽过程
        tasksContainer.addEventListener('dragover', (e) => {
            e.preventDefault();
            const containerRect = tasksContainer.getBoundingClientRect();
            const x = e.clientX - containerRect.left;
            const y = e.clientY - containerRect.top;

            // 计算相对于容器中心的坐标（转换为-50到50的范围）
            const relativeX = ((x / containerRect.width) - 0.5) * 100;
            const relativeY = (0.5 - (y / containerRect.height)) * 100;

            // 避免在坐标轴上放置任务点
            if (Math.abs(relativeX) < 2 || Math.abs(relativeY) < 2) return;

            // 确定象限
            const quadrant = getQuadrantFromCoordinates(relativeX, relativeY);
            if (!quadrant) return;

            const taskElement = document.querySelector('.dragging');
            if (taskElement) {
                // 更新任务点位置
                taskElement.style.left = `${(x / containerRect.width) * 100}%`;
                taskElement.style.top = `${(y / containerRect.height) * 100}%`;
            }
        });

        // 处理放下事件
        tasksContainer.addEventListener('drop', (e) => {
            e.preventDefault();
            const taskId = parseInt(e.dataTransfer.getData('text/plain'));
            const task = tasks.find(t => t.id === taskId);
            if (!task) return;

            const containerRect = tasksContainer.getBoundingClientRect();
            const x = e.clientX - containerRect.left;
            const y = e.clientY - containerRect.top;

            // 计算相对于容器中心的坐标
            const relativeX = ((x / containerRect.width) - 0.5) * 100;
            const relativeY = (0.5 - (y / containerRect.height)) * 100;

            // 避免在坐标轴上放置任务点
            if (Math.abs(relativeX) < 2 || Math.abs(relativeY) < 2) return;

            // 确定象限并更新任务
            const quadrant = getQuadrantFromCoordinates(relativeX, relativeY);
            if (!quadrant) return;

            // 更新任务数据
            task.x = relativeX;
            task.y = relativeY;
            task.quadrant = quadrant;

            // 保存并重新渲染
            saveTasksToLocalStorage();
            renderTasks();
        });
    }
}

// 根据坐标确定象限
function getQuadrantFromCoordinates(x, y) {
    if (x > 0 && y > 0) return 1;
    if (x < 0 && y > 0) return 2;
    if (x > 0 && y < 0) return 3;
    if (x < 0 && y < 0) return 4;
    return null;
}


// 保存任务到文件系统
function saveTasksToLocalStorage() {
    fetch('./data/assignments.json', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(tasks)
    }).catch(error => {
        console.error('保存任务失败:', error);
        // 如果保存到文件系统失败，回退到localStorage
        localStorage.setItem('quadrantTasks', JSON.stringify(tasks));
    });
}

// 从文件系统加载任务
function loadTasksFromLocalStorage() {
    fetch('./data/assignments.json')
        .then(response => response.json())
        .then(data => {
            tasks = data;
            renderTasks();
        })
        .catch(error => {
            console.error('加载任务失败:', error);
            // 如果从文件系统加载失败，尝试从localStorage加载
            const storedTasks = localStorage.getItem('quadrantTasks');
            if (storedTasks) {
                tasks = JSON.parse(storedTasks);
                renderTasks();
            }
        });
}

// 保存历史任务到文件系统
function saveHistoryTasksToLocalStorage() {
    fetch('./data/history.json', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(historyTasks)
    }).catch(error => {
        console.error('保存历史任务失败:', error);
        // 如果保存到文件系统失败，回退到localStorage
        localStorage.setItem('historyTasks', JSON.stringify(historyTasks));
    });
}

// 从文件系统加载历史任务
function loadHistoryTasksFromLocalStorage() {
    fetch('./data/history.json')
        .then(response => response.json())
        .then(data => {
            historyTasks = data;
            renderHistoryTasks();
        })
        .catch(error => {
            console.error('加载历史任务失败:', error);
            // 如果从文件系统加载失败，尝试从localStorage加载
            const storedHistoryTasks = localStorage.getItem('historyTasks');
            if (storedHistoryTasks) {
                historyTasks = JSON.parse(storedHistoryTasks);
                renderHistoryTasks();
            }
        });
}

// 关闭模态框
closeModalBtn.addEventListener('click', () => {
    modal.style.display = 'none';
});

// 关闭编辑模态框
closeEditModalBtn.addEventListener('click', () => {
    editModal.style.display = 'none';
});

// 点击模态框外部关闭
window.addEventListener('click', (e) => {
    if (e.target === modal) {
        modal.style.display = 'none';
    } else if (e.target === confirmDialog) {
        confirmDialog.style.display = 'none';
    } else if (e.target === editModal) {
        editModal.style.display = 'none';
    }
});

// 完成任务按钮点击事件
completeTaskBtn.addEventListener('click', completeTask);

// 编辑任务按钮点击事件
editTaskBtn.addEventListener('click', () => {
    const task = tasks.find(t => t.id === selectedTaskId);
    if (task) {
        // 填充编辑表单
        editTaskTitleInput.value = task.title;
        editTaskDescriptionInput.value = task.description;
        if (task.deadline) {
            // 将日期时间格式化为HTML datetime-local输入所需的格式 (YYYY-MM-DDThh:mm)
            const deadline = new Date(task.deadline);
            const year = deadline.getFullYear();
            const month = String(deadline.getMonth() + 1).padStart(2, '0');
            const day = String(deadline.getDate()).padStart(2, '0');
            const hours = String(deadline.getHours()).padStart(2, '0');
            const minutes = String(deadline.getMinutes()).padStart(2, '0');
            editTaskDeadlineInput.value = `${year}-${month}-${day}T${hours}:${minutes}`;
        } else {
            editTaskDeadlineInput.value = '';
        }

        // 关闭详情模态框，打开编辑模态框
        modal.style.display = 'none';
        editModal.style.display = 'block';
    }
});

// 编辑表单提交事件
editTaskForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const task = tasks.find(t => t.id === selectedTaskId);
    if (task) {
        // 更新任务数据
        task.title = editTaskTitleInput.value.trim();
        task.description = editTaskDescriptionInput.value.trim();
        task.deadline = editTaskDeadlineInput.value || null;

        // 保存到本地存储
        saveTasksToLocalStorage();

        // 重新渲染任务
        renderTasks();

        // 关闭编辑模态框
        editModal.style.display = 'none';
    }
});

// 确认删除按钮点击事件
confirmYesBtn.addEventListener('click', () => {
    const task = tasks.find(t => t.id === selectedTaskId);
    if (task) {
        // 从任务列表中移除
        tasks = tasks.filter(t => t.id !== selectedTaskId);
        // 添加到历史任务
        historyTasks.push(task);
        // 保存更新
        saveTasksToLocalStorage();
        saveHistoryTasksToLocalStorage();
        // 重新渲染任务点和任务列表
        renderTasks();
        renderHistoryTasks();
    }
    confirmDialog.style.display = 'none';
});

// 取消删除按钮点击事件
confirmNoBtn.addEventListener('click', () => {
    confirmDialog.style.display = 'none';
});